﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace eLearning.DosenView
{
    public partial class ListMemberPage : PhoneApplicationPage
    {
        private DetailMatkul matkul;
        private Perkuliahan kuliah;
        private bool searchMode;

        public ListMemberPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            NavigationService.RemoveBackEntry();
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.DETMATKUL))
            {
                matkul = (DetailMatkul)PhoneApplicationService.Current.State[Config.DETMATKUL];
                kuliah = new Perkuliahan();
                kuliah.DetMatkul = matkul;

                RefreshPage();
            }
        }

        private void LoadJoinedMember()
        {
            if (kuliah != null)
            {
                listJoined.Items.Clear();

                string url = string.Format("{0}&{1}", Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.VIEW_JOINED_MEMBER_KEY, Guid.NewGuid().ToString());
                string json = JsonConvert.SerializeObject(kuliah);

                Uri uri = new Uri(url, UriKind.Absolute);
                WebClient webClient = new WebClient();

                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listJoined_UploadStringCompleted);
                try
                {
                    webClient.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }

            }
        }

        private void listJoined_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            try
            {
                PerkuliahanList list = JsonConvert.DeserializeObject<PerkuliahanList>(e.Result);
                if (list.Count > 0)
                {
                    foreach (Perkuliahan kul in list)
                    {
                        Mahasiswa mahasiswa = kul.Mhs;
                        mahasiswa.Status = Mahasiswa.STATUS.NONE;
                        listJoined.Items.Add(mahasiswa);
                    }
                    PivotMember.SelectedIndex = 0;
                }
                else
                {
                    listJoined.ItemsSource = null;
                    if (searchMode)
                        MessageBox.Show("\"" +textBoxKeyword.Text + "\" tidak ditemukan");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadPendingMember()
        {
            if (kuliah != null)
            {
                listPending.Items.Clear();

                string url = string.Format("{0}&{1}", Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.VIEW_PENDING_MEMBER_KEY, Guid.NewGuid().ToString());
                string json = JsonConvert.SerializeObject(kuliah.DetMatkul);

                Uri uri = new Uri(url, UriKind.Absolute);
                WebClient webClient = new WebClient();

                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPendingMember_UploadStringCompleted);
                try
                {
                    webClient.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }

            }
        }

        private void listPendingMember_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;

            try
            {
                PerkuliahanList list = JsonConvert.DeserializeObject<PerkuliahanList>(e.Result);
                if (list.Count > 0)
                {
                    foreach (Perkuliahan kul in list)
                    {
                        Mahasiswa mahasiswa = kul.Mhs;
                        mahasiswa.Status = Mahasiswa.STATUS.JOIN;
                        listPending.Items.Add(mahasiswa);
                    }
                }
                else
                {
                    listPending.ItemsSource = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void AcceptAllPending()
        {
            Mahasiswa selectedMhs = getSelectedMahasiswa();
            kuliah.Mhs = selectedMhs;
            string json = JsonConvert.SerializeObject(kuliah);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(acceptPending_UploadStringCompleted);
            webClient.UploadStringAsync(new Uri(Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.ACCEPT_MEMBER_KEY, UriKind.Absolute), "POST", json);
        }

        private void acceptPending_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                {
                    return;
                }
                MessageBox.Show("Message : " + e.Result);
                RefreshPage();
            }
            catch (WebException ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void RejectAllPending()
        {
            Mahasiswa selectedMhs = getSelectedMahasiswa();
            kuliah.Mhs = selectedMhs;
            string json = JsonConvert.SerializeObject(kuliah);
            
            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(rejectPending_UploadStringCompleted);
            webClient.UploadStringAsync(new Uri(Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.REJECT_MEMBER_KEY, UriKind.Absolute), "POST", json);
        }

        private void rejectPending_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled && e.Error != null)
                {
                    return;
                }
                MessageBox.Show("Message : " + e.Result);
                RefreshPage();
            }
            catch (WebException ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void listMahasiswa_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                Mahasiswa mhs = (Mahasiswa)e.AddedItems[0];
                ((ListBox)sender).SelectedIndex = -1;

                if (PivotMember.SelectedIndex == 0)
                {
                    Utility.GotoPage(this, "/View/Dosen/MemberDetailPage.xaml");
                }
                else
                {
                    Utility.GotoPage(this, "/View/Dosen/MahasiswaDetailPage.xaml");
                }

                kuliah.Mhs = mhs;
                PhoneApplicationService.Current.State[Config.KULIAH] = kuliah;
            }
        }

        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            searchMode = false;
            kuliah.Mhs = null;
            RefreshPage();
            PivotMember.SelectedIndex = 0;
        }

        private void RefreshPage()
        {
            LoadJoinedMember();
            LoadPendingMember();
        }

        private void buttonAcceptAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Terima pendaftaran?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                AcceptAllPending();
        }

        private void buttonRejectAll_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Batalkan pendaftaran?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                RejectAllPending();
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            PivotMember.SelectedIndex = 2;
        }

        private void ManageButton(bool enable)
        {
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = enable;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[2]).IsEnabled = enable;
        }

        private void listPending_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ManageButton(listPending.SelectedItems.Count == 1);
        }

        private Mahasiswa getSelectedMahasiswa()
        {
            Mahasiswa mhs = new Mahasiswa();

            string[] ids = new string[listPending.SelectedItems.Count];
            for (int i = 0; i < listPending.SelectedItems.Count; i++)
            {
                Mahasiswa m = (Mahasiswa)listPending.SelectedItems[i];
                ids[i] = m.Id;
            }

            mhs.Id = string.Join("','", ids);
            return mhs;
        }

        private void textBoxKeyword_TextChanged(object sender, TextChangedEventArgs e)
        {
            buttonClear.IsEnabled = string.IsNullOrEmpty(textBoxKeyword.Text) ? false : true;
            buttonSearch.IsEnabled = string.IsNullOrEmpty(textBoxKeyword.Text) ? false : true;
        }

        private void buttonClear_Click(object sender, RoutedEventArgs e)
        {
            textBoxKeyword.Text = "";
        }

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxKeyword.Text.Length < 1)
            {
                MessageBox.Show("NIM/Nama is empty.");
                return;
            }
            searchMode = true;

            Mahasiswa find = new Mahasiswa();
            find.Nim = textBoxKeyword.Text;
            find.Nama = textBoxKeyword.Text;
            kuliah.Mhs = find;

            LoadJoinedMember();
        }
        
    }
}